<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="hAdd">添加角色

        </el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column align="center" width="200" label="角色">
          <template slot-scope="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" label="启用">

          <template slot-scope="{row}">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>
              {{ row.state === 1 ? "已启用" : "未启用" }}
            </span>

          </template>
        </el-table-column>
        <el-table-column align="center" label="描述">
          <template slot-scope="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <el-button type="text" size="small" @click="hOk(row)">确认</el-button>
              <el-button type="text" size="small" @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else>

              <el-button type="text" size="small" @click="hAssignPerm(row.id)"> 分配权限</el-button>
              <el-button type="text" size="small" @click="hEdit(row)">编辑</el-button>
              <el-popconfirm
                confirm-button-text="好的"
                cancel-button-text="不用了"
                icon="el-icon-info"
                icon-color="red"
                title="这是一段内容确定删除吗？"
                @onConfirm="hDel(row.id)"
              >
                <el-button slot="reference" type="text" size="small">删除</el-button>
              </el-popconfirm>

            </template>
          </template></el-table-column>

      </el-table>
      <!-- 放置分页组件 -->
      <el-row
        type="flex"
        style="height:60px"
        align="middle"
        justify="end"
      >
        <!-- 放置分页组件 -->
        <el-pagination
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pagesize"
          :current-page="pagesize"
          :page-sizes="[3,5,7]"
          @current-change="hCurrentChage"
          @size-change="hSizeChange"
        />
      </el-row>
    </div>

    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog">
      <!-- 表单内容 -->
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="roleForm.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <!-- 如果不需要校验 就不需要写 prop属性 -->
          <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />

        </el-form-item>
        <el-form-item>
          <el-button @click="hsave">取 消</el-button>
          <el-button type="primary" @click="doAdd">确 定</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>
    <!-- 传递id -->
    <AssignPermission ref="refPerm" :cur-id="curId" :show-dialog-perm.sync="showDialogPerm" />

  </div>
</template>

<script>

import { getRoleList, addRole, updataRole, delRole } from '@/api/role.js'
import AssignPermission from './components/assignPermission.vue'
export default {
  name: 'Role',
  components: {
    AssignPermission
  },
  data() {
    return {
      roleForm: {
        name: '测试',
        description: '描述信息',
        state: 1// 默认未1启用 关闭 0 打开1
      },
      curId: -1, // 当前操作的角色的id
      // showDialog: false, // 添加角色弹层
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      showDialog: false,
      showDialogPerm: false,
      list: [],
      total: 0,
      pagesize: 5,
      page: 1
    }
  },
  created() {
    this.loadRoleList()
  },
  methods: {
    hAssignPerm(id) {
      this.curId = id

      this.showDialogPerm = true

      // 调用子组件的方法，获取当前角色的权限
      this.$nextTick(() => {
        this.$refs.refPerm.getPermiss()
      })
    },
    async hDel(id) {
      // console.log(id)
      await delRole(id)
      // 提示用户
      this.$message.success('删除成功')
      if (this.page > 1) {
        this.page--
        // 重发请求,更新数据
        this.loadRoles()
      }
    },
    async hOk(row) {
      console.log(row)
      // 判断是否必填
      if (!row.editRow.name || !row.editRow.description) {
        this.$message.error('内容必填')
        return
      }
      // 调用接口
      await updataRole(row.editRow)
      this.$message.success('更新成功')
      // 退出编辑
      // eslint-disable-next-line require-atomic-updates
      row.isEdit = false
      // 重发请求,更新数据
      this.loadRoles()
    },
    hEdit(row) {
      // 启用编辑
      row.isEdit = true
    },
    // 点击确定
    doAdd() {
      this.$refs.roleForm.validate(async hAdd => {
        if (hAdd) {
          await addRole(this.roleForm)
          this.$message.success('新增角色成功')
          this.loadRoleList()
          this.hsave()
        }
        this.$refs.roleForm.resetFields()
        // 想要看到刚才添加的数据,要跳转到最后一页
        this.total = this.total + 1
        this.page = Math.ceil(this.total / this.pagesize)
        // 重发请求,更新数据
        this.loadRoles()
        this.showDialog = false // 关闭弹层
      })
    },
    hAdd() {
      this.showDialog = true
    },
    hsave() {
      this.$refs.roleForm.resetFields()
      this.showDialog = false // 关闭弹层
    },
    hCurrentChage(page) {
      // 更新页码
      this.page = page
      // 重发请求
      this.loadRoleList()
    },
    hSizeChange(pages) {
      this.pagesize = pages
      this.page = 1
      // 重发请求
      this.loadRoleList()
    },
    async loadRoleList() {
      const res = await getRoleList({ page: this.page, pagesize: this.pagesize })
      console.log(res.data)
      this.list = res.data.rows
      // 给每一行都补充一个属性： isEdit，用来标记当前行是否处于编辑状态
      this.list.forEach(it => {
        // this.$set(对象，新添加的属性名，属性值)
        // 这样补充的属性是响应式的 ===> 改了值，视图会变化
        this.$set(it, 'isEdit', false)
        // 缓存-备份数据
        this.$set(it, 'editRow', {
          id: it.id,
          name: it.name,
          state: it.state,
          description: it.description
        })
        // it.isEdit = true
      })

      console.log(this.list)
      this.total = res.data.total
    }
  }
}
</script>

<style scoped>
.role-operate {
  padding: 10px;
}
</style>
